﻿// Copyright © 2011 Paul Vanukoff (pvanukoff@gmail.com)

namespace Bravura.Native.PluginBase.Waveforms
{
	/// <summary>
	/// A waveform sourced from an array.
	/// </summary>
	/// <remarks>
	/// Uses linear interpolation.
	/// </remarks>
	public class DataTableWaveform : Waveform
	{
		private double[] _data;
		private int _len;

		public DataTableWaveform()
		{
			SetData(new double[1]);
		}

		public DataTableWaveform(double[] data)
		{
			SetData(data);
		}

		public void SetData(double[] data)
		{
			_len = data.Length;
			_data = new double[_len + 1];

			// copy data
			for (int i = 0; i < _len; i++)
			{
				_data[i] = data[i];
			}

			// copy first sample into last position to support interpolation of the last sample
			_data[_len] = data[0];
		}

		#region Waveform Implementation

		public override double GetValue(double angle)
		{
			double realPos = angle * _len;
			int intPos = (int)realPos;
			double val0 = _data[intPos];
			double val1 = _data[intPos + 1];
			double mix = realPos - intPos;
			return mix * val1 + (1.0 - mix) * val0;
		}

		#endregion
	}
}
